<template>
  <div class="cc-form-filter">
    <div>
      <div class="select-box">
        <span>所有分类：</span>
        <span
          v-for="(item, index) in selectItems"
          :key="item.key"
          class="item"
          @click="onRemove(index)"
        >
          {{ item.text }}
          <i class="icon iconfont icon_guanbi" />
        </span>
      </div>
      <div v-for="type of types" :key="type.key" class="row">
        <span class="name">{{ type.text }}：</span>
        <span
          class="item"
          v-for="item of type.items"
          :key="item.value"
          @click="onItem(type, item)"
        >{{ item.text }}</span>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'CCFormFilter',
    props: {
      types: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        selectItems: []
      };
    },

    methods: {
      onRemove(index) {
        this.selectItems.splice(index, 1);
        this.onChange();
      },

      onItem(type, item) {
        const index = this.selectItems.findIndex(obj => {
          return obj.key === type.key;
        });
        const newItem = {
          text: item.text,
          key: type.key,
          value: item.value
        };
        if (index >= 0) {
          this.selectItems.splice(index, 1, newItem);
        } else {
          this.selectItems.push(newItem);
        }
        this.onChange();
      },

      onChange() {
        const obj = {};
        for (const item of this.selectItems) {
          const key = item.key || '';
          obj[key] = item.value;
        }
        this.$emit('change', obj);
      }
    },

    created() {}
  };
</script>
<style lang="scss" type="text/scss" scoped>
$space: 12px;
.cc-form-filter {
  background: white;
  padding: $space + 8;
  margin-top: $space;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  font-size: 14px;
  .row {
    margin-top: 12px;
    .item {
      padding: 0 12px;
      color: gray;
      cursor: pointer;
    }
  }
  .name {
    color: gray;
    width: 100px;
    text-align: justify;
    text-justify: inter-cluster;
  }
}

.select-box {
  margin-bottom: 20px;
  color: $t1;
  .item {
    border: 1px solid gray;
    margin: 0 10px;
    padding: 1px 8px;
    .icon_guanbi {
      font-size: 4px;
    }
  }
}
</style>
